/*
 * Copyright (c) 2021 IBM Corp and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    https://www.eclipse.org/legal/epl-2.0/
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Seth Hoenig
 *    Allan Stockdill-Mander
 *    Mike Robertson
 */

package main

import (
	"fmt"
	"github.com/eclipse/paho.mqtt.golang"
	"os"
	"strconv"
	"time"
)

var record int

var f2 mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	//fmt.Println("f2本机器")
	//fmt.Println(time.Now().String())
	//fmt.Println("topic： ", msg.Topic())
	//fmt.Println("收到数据长度: ", len(msg.Payload()))
	record++
	fmt.Println(record)
}


func main() {
	//mqtt.DEBUG = log.New(os.Stdout, "", 0)
	//mqtt.ERROR = log.New(os.Stdout, "", 0)
	dur, err := strconv.Atoi(os.Args[1])
	if err != nil {
		return
	}
	fmt.Println("连接个数； ", dur)

	staticId := "hz_"
	for i := 0; i < dur;i++ {
		opts := mqtt.NewClientOptions().AddBroker("tcp://192.168.20.80:1883")
		opts.SetClientID(staticId + strconv.Itoa(i))

		c := mqtt.NewClient(opts)
		defer func() {
			//fmt.Println("断开连接")
			//c.Disconnect(250)
		}()
		token := c.Connect()
		if token.Wait() && token.Error() != nil {
			panic(token.Error())
		}

		if token = c.Subscribe("/dev/41/42/#", 0, f2); token.Wait() && token.Error() != nil {
			fmt.Println(token.Error())
			return
		}

		time.Sleep(time.Millisecond)
	}

	for {
		time.Sleep(time.Second * 30)
	}
}
